package com.fulu.netty.luban.onereactor;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

/**
 * 读取数据，处理业务逻辑类
 */
public class TCPHandler implements Runnable {

    private final SelectionKey key;
    private final SocketChannel socketChannel;

    public TCPHandler(SelectionKey key, SocketChannel socketChannel) {
        this.key = key;
        this.socketChannel = socketChannel;
    }


    @Override
    public void run() {
        byte[] arr = new byte[1024];
        ByteBuffer buf = ByteBuffer.wrap(arr);
        int numBytes = 0;
        try {
            numBytes = socketChannel.read(buf);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 没有读到数据
        if(numBytes == -1){
            System.out.println("[warning]客户端断开连接。");
            closeChannel();
            return;
        }

        String s = new String(arr);
        if(s != null && !"".equals(s)){
            process(); //处理业务逻辑
            System.out.println(socketChannel.socket().getRemoteSocketAddress().toString() + " > " + s);
            ByteBuffer returnBuf = ByteBuffer.wrap("服务端返回".getBytes());
            try {
                while (returnBuf.hasRemaining()){
                    socketChannel.write(returnBuf); // 回传给client
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 模拟处理业务逻辑
     */
    private void process() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭服务
     */
    private void closeChannel() {
        try {
            key.cancel();
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
